package io2.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class AIOClient {
    static CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException {
        AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8080),
                socketChannel, new CompletionHandler<Void, AsynchronousSocketChannel>() {
                    @Override
                    public void completed(Void result, AsynchronousSocketChannel attachment) {
                        System.out.println("连接成功");
                        ByteBuffer buffer = ByteBuffer.wrap("getTime".getBytes());
                        // 发送消息
                        attachment.write(buffer, buffer, new WriteCompletionHandler(attachment));
                    }

                    @Override
                    public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
                        System.out.println("连接失败");
                        exc.printStackTrace();
                    }
                });
        latch.await();
        socketChannel.close();
    }

    private static class WriteCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

        AsynchronousSocketChannel socketChannel;

        public WriteCompletionHandler(AsynchronousSocketChannel socketChannel) {
            this.socketChannel = socketChannel;
        }

        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            if(!attachment.hasRemaining()) {
                System.out.println("消息写入完成");
            }
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 读取返回的数据
            socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println("result -> " + result);
                    attachment.flip();
                    byte[] bytes = new byte[attachment.remaining()];
                    attachment.get(bytes);
                    System.out.println("收到数据 -> " + new String(bytes));
                    latch.countDown();
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.out.println("接收数据失败");
                    latch.countDown();
                }
            });
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            System.out.println("消息写入失败");
            exc.printStackTrace();
            latch.countDown();
        }
    }
}
